package org.example;

import org.springframework.util.StringUtils;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Map;

/**
 * @author topto
 * 请求
 */
public class HttpSend {
    public static String sendHttp(String targetUrl,String data,String method,Map<String,String> map) throws Exception {
        // 构造 URL 对象
        URL url = new URL(targetUrl);

        // 打开 HTTP 连接
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();

        // 设置请求方法
        connection.setRequestMethod(method);
        connection.setRequestProperty("Content-Type", "application/json");
        if(map!=null){
            for(Map.Entry<String,String> e:map.entrySet()){
                connection.setRequestProperty(e.getKey(),e.getValue());
            }
        }
        // 设置是否向 URL 连接输出，因为这个是 POST 请求，参数要放在 http 正文内
        connection.setDoOutput(true);

        // 构造请求体
        if(!StringUtils.isEmpty(data)){
            String requestBody = data;

            // 将请求体写入 HTTP 正文
            OutputStream os = connection.getOutputStream();
            os.write(requestBody.getBytes());
            os.flush();
            os.close();
        }
        // 获取返回数据
        BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        StringBuilder response = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            response.append(line);
        }
        reader.close();

        String res=response.toString();
        return res;
    }
}
